<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" :isSearchDisabled="isSearchDisabled" @reset="resetPage">
      <el-col :span="8" :xs="24" v-show="$permiss[205]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select style="width: 100%" @change="tenantChange" v-model="page.adminUserId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')">
          <el-input v-model="page.idcard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[206]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[207]">
        <el-form-item :label="$t('操作人')" prop="inputName">
          <el-select style="width: 100%" v-model="page.inputName" clearable>
            <el-option v-for="(item,index) in remissionUser" :key="item+index" :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[812]">
        <el-form-item :label="$t('减免类型')" prop="cause1">
          <el-select style="width: 100%" v-model="page.cause1" clearable>
            <el-option v-for="item in remissionTypeList" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[812]">
        <el-form-item :label="$t('减免状态')">
          <el-select style="width: 100%" v-model="page.status" clearable>
            <el-option :value="1" :label="$t('通过')"></el-option>
            <el-option :value="2" :label="$t('审核中')"></el-option>
            <el-option :value="3" :label="$t('拒绝')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('减免时间')" prop="reductionTime">
          <el-date-picker
              v-model="page.reductionTime"
              style="width: 100%"
              unlink-panels
              type="daterange"
              value-format="yyyy-MM-dd"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')" prop="applyTime">
          <el-date-picker
              v-model="page.applyTime"
              style="width: 100%"
              unlink-panels
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <div style="text-align: right;margin-bottom: 10px" v-show="$permiss[783]">
        <el-button type="primary" @click="exportsExcel" :loading="exportsLoading">{{ $t('导出') }}</el-button>
      </div>
      <Table :loading="loading" :page="page" :table-data="tableData"
             :table-column="tableColumn"
             @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <template slot-scope="{row}" slot="certificate">
          <el-image v-if="row.certificate" style="height: 80px;" :src="row.certificate"
                    :preview-src-list="[row.certificate]"></el-image>
        </template>
        <template slot="result" slot-scope="{row}">
          {{
            formatRemission(row.remissionResult)
          }}
        </template>
        <template slot-scope="{row}" slot="handle">
          <el-button :disabled="row.status !== 2" type="text" @click="toExamine(row)" v-show="$permiss[1004]">
            {{ $t('审核') }}
          </el-button>
        </template>
      </Table>
    </el-card>

    <!--     减免审批-->
    <Dialog :visible.sync="visibleApproval" :title="$t('减免审批')" width="45%" @cancel="visibleApproval = false"
            @confirm="approvalConfirm()" :confirm-loading="confirmLoading" @close="approvalClose()">
      <el-form label-width="80px" ref="form" :model="approvalForm">
        <el-form-item :label="$t('减免金额')">
          <div style="line-height: 32px">
            {{ tableRows.remissionAmount }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('减免类型')">
          <div style="line-height: 32px">
            {{ tableRows.cause1 }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('减免原因')">
          <div style="line-height: 32px">
            {{ tableRows.cause2 }}
          </div>
        </el-form-item>
        <el-form-item v-if="tableRows.certificate" :label="$t('凭证')">
          <div style="width: 200px;height: 150px">
            <el-image style="width: 100%;height: 100%" :src="tableRows.certificate"
                      :preview-src-list="[tableRows.certificate]"></el-image>
          </div>
        </el-form-item>
        <el-form-item :label="$t('结果')" prop="remissionResult" :rules="[{required: true, message: this.$t('不能为空')}]">
          <el-select v-model="approvalForm.remissionResult" @change="remissionResultChange">
            <el-option :label="$t('通过')" :value="1"></el-option>
            <el-option :label="$t('拒绝')" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showResult" :label="$t('原因')" prop="approvalReason"
                      :rules="[{required: true, message: this.$t('不能为空')}]">
          <el-select v-model="approvalForm.approvalReason" @change="reasonChange">
            <el-option v-for="item in remissionResult" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark" :required="remarkRules"
                      :rules="remarkRules ? [  {required: true, message: this.$t('不能为空')}] : []">
          <el-input type="textarea" :rows="5" v-model="approvalForm.remark"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {export_json_to_excel} from "@/utils/exportExcel";
import {defaultTimeDate} from '@/utils/tools'
import {selectTenant, selectProduct,} from "@/api/system";
import {
  remissionPageHelper,
  remissionCause,
  remissionApprovalCause,
  remissionApproval,
  remissionExcel,
  selectRemissionUser
} from '@/api/finance'
import {dateFormatSection} from '@/utils/tools'
export default {
  name: 'reductionRecord',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        applyTime: defaultTimeDate(7),
      },
      tableData: [],
      remissionTypeList: [],
      tableColumn: [
        {label: this.$t('订单编号'), prop: 'loanRecordId', fixed: 'left', align: 'center', width: 150},
        {label: this.$t('用户姓名'), prop: 'name', align: 'center',},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center', width: 100},
        {label: this.$t('身份证'), prop: "idCard", align: "center", width: 100,},
        {label: this.$t('合同金额'), prop: 'passAmount', align: 'center', width: 120},
        {label: this.$t('打款金额'), prop: 'dealAmount', align: 'center', width: 120},
        {label: this.$t('应还金额'), prop: 'value', align: 'center', minWidth: 100},
        {label: this.$t('利息'), prop: 'interestValue', align: 'center', minWidth: 100},
        {label: this.$t('逾期罚息'), prop: 'overdueValue', align: 'center',},
        {label: this.$t('应还款时间'), prop: 'refundDate', align: 'center', minWidth: 150},
        {label: this.$t('已还金额'), prop: 'actualPayAmount', align: 'center', minWidth: 100},
        {label: this.$t('减免金额'), prop: 'remissionAmount', align: 'center', minWidth: 100},
        {label: this.$t('优惠券预抵扣'), prop: 'expectDeduction', align: 'center', minWidth: 120},
        {label: this.$t('减免类型'), prop: 'cause1', align: 'center', minWidth: 100},
        {label: this.$t('减免原因'), prop: 'cause2', align: 'center', minWidth: 100},
        {label: this.$t('备注'), prop: 'remark', align: 'center', minWidth: 150},
        {label: this.$t('凭证'), align: 'center', slot: 'certificate', prop: 'certificate', width: 150},
        {label: this.$t('减免申请人'), prop: 'approvalPeople', align: 'center', minWidth: 120},
        {label: this.$t('申请时间'), prop: 'approvalTime', align: 'center', minWidth: 150},
        {label: this.$t('减免结果'), prop: 'remissionResult', slot: 'result', align: 'center',},
        {label: this.$t('审批原因'), prop: 'approvalReason', align: 'center',},
        {label: this.$t('操作人'), prop: 'inputUserId', align: 'center',},
        {label: this.$t('操作时间'), prop: 'inputTimestamp', align: 'center', width: 150},
        {label: this.$t('APP名称'), prop: 'appName', align: 'center', width: 150},
        {label: this.$t('所属租户'), align: "center", prop: 'adminUserName', isHide: !this.$permiss[205]},
        {label: this.$t('操作'), align: "center", slot: 'handle', fixed: 'right', isHide: !this.$permiss[1003]},
      ],
      loading: false,
      tenantList: [],
      productList: [],
      remissionUser: [],
      exportsLoading: false,
      visibleApproval: false,
      tableRows: {},
      approvalForm: {},
      remissionResult: [],
      showResult: false,
      remarkRules: false,
      confirmLoading: false,
      isSearchDisabled: false
    }
  },
  mounted() {

    this.getTableData()
    this.getSelectList()
  },
  methods: {
    async getTableData() {
      this.loading = true
      this.isSearchDisabled = true
      const reductionTime = dateFormatSection(this.page.reductionTime || [])
      const [approvalTimeStart, approvalTimeEnd] = dateFormatSection(this.page.applyTime || [])
      const params = Object.assign({}, this.page, {
        datetimeStart: reductionTime && reductionTime.length > 1 ? reductionTime[0] : undefined,
        datetimeEnd: reductionTime && reductionTime.length > 1 ? reductionTime[1] : undefined,
        approvalTimeStart, approvalTimeEnd
      })
      // 删除日期属性
      delete params.reductionTime
      delete params.applyTime
      const res = await remissionPageHelper(params)
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.tableData = list
        this.page = Object.assign({}, this.page, {
          pageNum: pageNum,
          pageSize: pageSize,
          total: total
        })
        this.loading = false
        this.isSearchDisabled = false
      } else {
        this.loading = false
        this.isSearchDisabled = false
      }
    },
    async getRemissionCause() {
      const res = await remissionCause()
      if (res.code === 1) {
        this.remissionTypeList = [...res.data].filter(i => i.code === 0)
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page,'productName', null)
      })
    },
    async getSelectList() {
      selectTenant().then(res => {
        this.tenantList = res.data
      })
      selectProduct().then(res => {
        this.productList = res.data
      })
      selectRemissionUser().then(res => {
        this.remissionUser = res.data
      })
      if (this.$permiss[812]) {
        this.getRemissionCause()
      }
    },
    resetPage() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },
    // 去审核
    toExamine(row) {
      this.tableRows = {...row}
      this.visibleApproval = true
    },
    /**
     * 减免结果下拉
     */
    async remissionResultChange(value) {
      // 拒绝显示原因
      if (value === 2) {
        this.showResult = true
        const res = await remissionApprovalCause()
        if (res.code === 1) {
          this.remissionResult = res.data
        }
      } else {
        this.$set(this.approvalForm, 'approvalReason', undefined)
        this.showResult = false
      }
    },
    /**
     * 审核提交
     */
    approvalConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          this.confirmLoading = true
          const res = await remissionApproval({
            ...this.approvalForm,
            remissionId: this.tableRows.remissionId
          })
          if (res.code === 1) {
            this.confirmLoading = false
            this.visibleApproval = false
            this.$message.success(this.$t('操作成功'))
            this.getTableData()
          } else {
            this.confirmLoading = false
          }
        }
      })
    },
    approvalClose() {
      this.showResult = false
      this.approvalForm = {}
      this.$refs.form.resetFields()
    },
    reasonChange(key) {
      const result = this.remissionResult.filter(item => item.key === key)[0]
      if (result.isRemark === 1) {
        this.remarkRules = true
      } else {
        this.remarkRules = false
      }
    },
    formatRemission(value) {
      let str = ''
      switch (value) {
        case 1 :
          str = this.$t('通过')
          break;
        case 2:
          str = this.$t('拒绝')
          break;
        case 3 :
          str = this.$t('审核中')
      }
      return str
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.reductionTime || [])
      const [approvalTimeStart, approvalTimeEnd] = dateFormatSection(this.page.applyTime || [])
      const params = {
        ...this.page,
        datetimeStart, datetimeEnd,
        approvalTimeStart, approvalTimeEnd
      };
      delete params.reductionTime;
      delete params.applyTime;
      const res = await remissionExcel(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.avoidAudit = item.avoidAudit === 1 ? this.$t('是') : this.$t('否')
          item.remissionResult = this.formatRemission(item.remissionResult)
          return item
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("减免记录");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
  }
}
</script>

<style scoped>

</style>
